package com.acme.bankapp.service.bank;

import java.util.LinkedList;
import java.util.Queue;

import com.acme.bankapp.domain.bank.EMail;

/**
 * Class {@code EMailService} implements sending e-mails routine.
 * @author Artem Nikitin
 *
 */
public class EMailService implements Runnable {
	
	private Queue<EMail> outboxQueue;
	private volatile boolean isStopped;
	
	public EMailService() {
		outboxQueue = new LinkedList<>();
		new Thread(this).start();
	}
	
	@Override
	public void run() {
		while (!isStopped) {
			synchronized (outboxQueue) {
				try {
					while (outboxQueue.isEmpty()) {
						outboxQueue.wait();
					}
					sendPendingEMails();
				} catch (InterruptedException e) {
					System.out.println("Service has been interrupted");
					isStopped = true;
				}
			}
		}
		
	}
	
	/**
	 * Puts email into outbox queue.
	 * @param eMail - mail object
	 * @throws IllegalStateException - if service is stopped
	 */
	public void sendMail(EMail eMail) {
		if (isStopped) {
			throw new IllegalStateException("Service is stopped");
		}
		synchronized (outboxQueue) {
			outboxQueue.add(eMail);
			outboxQueue.notifyAll();
		}
	}
	
	/**
	 * Sends all emails that are in outbox queue
	 */
	private void sendPendingEMails() {
		synchronized (outboxQueue) {
			while (!outboxQueue.isEmpty()) {
				EMail mail = outboxQueue.remove();
				System.out.println("Sending mail... " + mail);
			}
		}
	}
	
	/**
	 * Closes service. Service is no longer available after this method call 
	 */
	public void close() {
		synchronized (outboxQueue) {
			isStopped = true;
			outboxQueue.notifyAll();
		}
	}
}
